<?php
/**
 * Created by PhpStorm.
 * User: HHZ
 * Date: 2018/12/4
 * Time: 11:07
 */

namespace Biz\module\Classes\adm;

use Biz\cache\AllActivityBak;
use Biz\pockets\excel\UpExcel;
use Biz\pockets\excel\ReadExcel;
use Biz\service\activity\AllactivityInfoBak;
use Biz\service\Goods as sGoods;
use Biz\service\Sku as sSku;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\cache\FlashSale as cFlashSale;
use Biz\model\activity\FlashSale as mFlashSale;
use Biz\model\activity\LimitTimeRobbing as mLimitTimeRobbing;
use Biz\model\activity\LimitTimeRobbingSku as mLimitTimeRobbingSku;
use Biz\model\activity\AllActivityGoods as mAllActivityGoods;
use Biz\model\activity\AllActivitySku as mAllActivitySku;
use Biz\service\activity\AllActivityInfo;
use Biz\service\ShopInfo as sShopInfo;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Doraemon\tools\Log as tLog;
use Doraemon\tools\Log;

class FlashSale
{

    const ALL_ACTIVITY_MAP = [
        ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB => AllActivityInfo::ALL_ACTIVITY_TYPE_FLASH_SALE,
        ActivityInfo::ACTIVITY_TYPE_ZHUYOUJINTIE => AllActivityInfo::ALL_ACTIVITY_TYPE_JINTIE,
    ];

    /**
     * 限时购是否能修改 -- 在执行修改的操作的时候调用.
     * @param $flashSaleId
     * @return bool
     */
    private static function isCanUpdate($flashSaleId)
    {
        $time = time();
        $flashSale = mFlashSale::get('*', ['id' => $flashSaleId]);
        $startTime = strtotime($flashSale['start_time']);
        $endTime = strtotime($flashSale['end_time']);
        if($time >  $endTime) {
            return false;
        }
        return true;
    }

    /**
     * 批量商品
     * @param $file
     * @param $isConfirm
     * @param $adminId
     * @return array|bool
     * @throws \Exception
     */
    public static function upLoadGoods($file, $isConfirm, $adminId)
    {
        // 读取数据
        $data = self::getData($isConfirm, $file);
        if($data === false) {
            return false;
        }

        if(empty($data)) {
            return ['code' => 1, 'msg' => '文件不能为空'];
        }

        // 验证活动价格， 删除不符合规则的sku
        $invalidSkuIdList = self::checkPrice($data);
        if(!$data) {
            $invalidSkuIdList = implode('、', $invalidSkuIdList);
            tLog::debug('部分sku价格不符合规则', [$invalidSkuIdList]);
            return ['code' => 1, 'msg' => '部分商品因价格高于同时段的商家直降价，未能上传成功，SKU ID如下：' . $invalidSkuIdList];
        }

        // 验证商品和sku是否存在
        $goodsIds = array_column($data, 'goods_id');
        $result = self::checkGoods($goodsIds, $data);
        if($result !== true) {
            tLog::debug('商品或者sku不存在', [$result, $data]);
            return $result;
        }

        // 二次确认价格
        $skuInfo = sSku::Sku($goodsIds, sSku::FIELDS_GROUP_SKU_INFO, ['activity_type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB]);
        $goodsInfo = sGoods::Goods($goodsIds, sGoods::FIELDS_GROUP_BASE, ['activity_type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB]);
        $result = self::confirm($isConfirm, $data, $skuInfo);
        if($result !== true) {
            tLog::debug('价格有误', [$result, $data]);
            return $result;
        }

        // 将时间转换为 Y-m-d H:i:s格式
        $data = self::formatTime($data);

        // 验证文件内的时间是否冲突
        $result = self::checkFileTime($data);
        if($result !== true) {
            tLog::debug('文件中的时间冲突', $data);
            return $result;
        }

        // 构造以时间为key的数据
        $list = self::formatList($data);

        // 检验与其他场次是否冲突
        $result = self::checkFlashSaleTime($list);
        if($result !== true) {
            tLog::debug('限时抢场次时间冲突', [$result, $list]);
            return $result;
        }

        // 验证商品下的sku价格、限购数量、卖点 是否一致
        $result = self::checkSkuActivityPrice($list);
        if($result !== true) {
            tLog::debug('请检测商品下的sku价格、限购数量、卖点 是否一致', $list);
            return $result;
        }

        // 验证商品是否与其他活动里的冲突
        $result = self::checkGoodsActivityTime($list);
        if($result !== true) {
            tLog::debug('商品存在于其他活动中', [$result, $list]);
            return $result;
        }

        // 构造批量添加所需要的数据
        $flashSaleData = self::formatFlashData($adminId, $list, $goodsInfo, $skuInfo);

        $result = mFlashSale::action(function () use($adminId, $flashSaleData, $list) {
            foreach ($flashSaleData as $flashSaleInfo) {
                // 添加基础表
                $result = mFlashSale::insert($flashSaleInfo['flash_sale'])->rowCount();
                if($result) {
                    $flashSaleId = mFlashSale::id();
                } else {
                    return false;
                }

                // 添加限时抢goods维度表
                $result = self::addLimitTimeRobbing($flashSaleId, $flashSaleInfo['limit_time_robbing']);
                if(!$result) {
                    return false;
                }

                // 添加限时抢sku维度表
                $result = self::addLimitTimeRobbingSku($flashSaleInfo['flash_sale'], $flashSaleInfo['limit_time_robbing_sku']);
                if(!$result) {
                    return false;
                }

                // 添加总活动的goods表和sku维度表
                $result = self::addAllActivityGoods($flashSaleId, $flashSaleInfo['all_activity_goods'], $flashSaleInfo['all_activity_sku']);
                if(!$result) {
                    return false;
                }
            }
            return true;
        });

        if($invalidSkuIdList !== true) {
            $invalidSkuIdList = implode('、', $invalidSkuIdList);
            return ['code' => 1, 'msg' => '部分商品因价格高于同时段的商家直降价，未能上传成功，SKU ID如下：' . $invalidSkuIdList];
        }

        return $result;
    }

    /**
     * 限时抢goods维度表添加
     * @param $flashSaleId
     * @param $limitTimeRobbing
     * @return mixed
     */
    private static function addLimitTimeRobbing($flashSaleId, $limitTimeRobbing)
    {
        foreach ($limitTimeRobbing as $key => $info) {
          $limitTimeRobbing[$key]['flash_sale_id'] = $flashSaleId;
        }
        $result = mLimitTimeRobbing::insert($limitTimeRobbing)->rowCount();
        return $result;
    }

    /**
     * 限时抢sku维度表添加
     * @param $flashSaleInfo
     * @param $limitTimeRobbingSku
     * @return bool
     */
    private static function addLimitTimeRobbingSku($flashSaleInfo, $limitTimeRobbingSku)
    {
        $goodsIds = array_keys($limitTimeRobbingSku);
        $startTime = array_column($flashSaleInfo, 'start_time')[0];
        $endTime = array_column($flashSaleInfo, 'end_time')[0];

        $result = mLimitTimeRobbing::select_master(['id', 'goods_id'], [
            'AND' => [
                'goods_id' => $goodsIds,
                'start_time' => $startTime,
                'end_time' => $endTime,
                'status' => mLimitTimeRobbingSku::STATUS_NORMAL
            ]
        ]);

        foreach ($limitTimeRobbingSku as $goodsId => $info) {
            foreach ($info as $key =>  $item) {
                foreach ($result as $value) {
                    if($item['goods_id'] == $value['goods_id']) {
                        $limitTimeRobbingSku[$goodsId][$key]['robbing_id'] = $value['id'];
                        break;
                    }
                }
            }

            $skuResult = mLimitTimeRobbingSku::insert(array_values($limitTimeRobbingSku[$goodsId]))->rowCount();
            if(!$skuResult) {
                return false;
            }
        }
        return true;
    }

    /**
     * 添加总活动的goods表和sku维度表
     * @param $flashSaleId
     * @param $allActivityGoods
     * @param $allActivitySku
     * @return bool
     */
    private static function addAllActivityGoods($flashSaleId, $allActivityGoods, $allActivitySku)
    {
        foreach ($allActivityGoods as $key => $info) {
            $allActivityGoods[$key]['activity_id'] = $flashSaleId;
        }

        foreach ($allActivitySku as $key => $info) {
            $allActivitySku[$key]['activity_id'] = $flashSaleId;
        }

        $flashSale = mFlashSale::get('*', ['id' => $flashSaleId]);
        $type = $flashSale['type'] ?? AllActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB;
        $result = AllActivityInfo::admUpdateActivityInfo($flashSaleId, $type, $allActivityGoods, $allActivitySku, self::ALL_ACTIVITY_MAP[$type]);
        if(!$result) {
            return false;
        }
        return true;
    }

    /**
     * 构造需要添加的总数据
     * @param $adminId
     * @param $list
     * @param $goodsInfo
     * @param $skuInfo
     * @return array
     */
    private static function formatFlashData($adminId, $list, $goodsInfo, $skuInfo)
    {
        $flashData = [];
        foreach ($list as $key => $goods) {
            $time = explode('~', $key);
            $flashData[] = [
                'flash_sale' => self::formatFlashSale($adminId, $time),
                'limit_time_robbing' => self::formatLimitTimeRobbing($adminId, $goods, $goodsInfo),
                'limit_time_robbing_sku' => self::formatLimitTimeRobbingSku($adminId, $goods, $goodsInfo),
                'all_activity_goods' => self::formatAllActivityGoods($goods, $goodsInfo),
                'all_activity_sku' => self::formatAllActivitySku($goods, $goodsInfo, $skuInfo),
            ];

        }
        return $flashData;
    }

    /**
     * 构造flash_sale表的数据
     * @param $adminId
     * @param $time
     * @return array
     */
    private static function formatFlashSale($adminId, $time)
    {
        $flashSale[] = [
            'type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB,
            'start_time' => $time[0],
            'end_time' => $time[1],
            'addtime' => date('Y-m-d H:i:s'),
            'admin_id' => $adminId,
        ];
        return $flashSale;
    }

    /**
     * 构造limit_time_robbing表的数据
     * @param $adminId
     * @param $goods
     * @param $goodsInfo
     * @return array
     */
    private static function formatLimitTimeRobbing($adminId, $goods, $goodsInfo)
    {
        $limitTimeRobBingList = [];
        $order = 0;
        foreach ($goods as $key => $info) {
            $limitTimeRobBingList[$info['goods_id']] = [
                'goods_id' => $info['goods_id'],
                'shop_id' => $goodsInfo[$info['goods_id']]['uid'],
                'describe' => $info['describe'],
                'order' => $order,
                'buy_price' => $info['activity_price'],
                'buy_limit' => $info['limit_buy_count'],
                'start_time' => $info['start_time'],
                'end_time' => $info['end_time'],
                'add_time' => date('Y-m-d H:i:s'),
                'admin_id' => $adminId,
                'status' => mLimitTimeRobbing::STATUS_NORMAL,
            ];
            $order++;
        }
        return $limitTimeRobBingList ? array_values($limitTimeRobBingList) : [];
    }

    /**
     * 构造limit_time_robbing_sku表的数据
     * @param $adminId
     * @param $goods
     * @param $goodsInfo
     * @return array
     */
    private static function formatLimitTimeRobbingSku($adminId, $goods, $goodsInfo)
    {
        $limitTimeRobBingSkuList = [];
        foreach ($goods as $key => $info) {
            $limitTimeRobBingSkuList[$info['goods_id']][$info['sku_id']] = [
                'goods_id' => $info['goods_id'],
                'shop_id' => $goodsInfo[$info['goods_id']]['uid'],
                'sku_id' => $info['sku_id'],
                'promo_stock' => $info['stock'],
                'buy_price' => $info['activity_price'],
                'start_stock' => $info['stock'],
                'start_time' => $info['start_time'],
                'end_time' => $info['end_time'],
                'addtime' => date('Y-m-d H:i:s'),
                'action_uid' => $adminId,
                'status' => mLimitTimeRobbingSku::STATUS_NORMAL,
            ];
        }

        return $limitTimeRobBingSkuList ?  : [];
    }

    /**
     * 构造all_Activity_goods表数据
     * @param $goods
     * @param $goodsInfo
     * @return array
     */
    private static function formatAllActivityGoods($goods, $goodsInfo)
    {
        $allActivityGoodsList = [];
        foreach ($goods as $key => $info) {
            $allActivityGoodsList[$info['goods_id']] = [
                'type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB,
                'shop_id' => $goodsInfo[$info['goods_id']]['uid'],
                'goods_id' => $info['goods_id'],
                'start_time' => $info['start_time'],
                'end_time' => $info['end_time'],
                'preview_start_time' => $info['start_time'],
                'real_start_time' => $info['start_time'],
                'real_end_time' => $info['end_time'],
                'status' => mAllActivityGoods::STATUS_NORMAL,
                'addtime' => date('Y-m-d H:i:s'),
            ];
        }
        return $allActivityGoodsList ? array_values($allActivityGoodsList) : [];
    }

    /**
     * 构造all_Activity_sku表数据
     * @param $goods
     * @param $goodsInfo
     * @param $skuInfo
     * @return array
     */
    private static function formatAllActivitySku($goods, $goodsInfo, $skuInfo)
    {
        $list = [];
        foreach ($skuInfo as $info) {
            foreach ($info as $item) {
                $list[$item['sku_id']] = $item;
            }
        }

        $allActivitySkuList = [];
        foreach ($goods as $key => $info) {
            $allActivitySkuList[$info['sku_id']] = [
                'type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB,
                'shop_id' => $goodsInfo[$info['goods_id']]['uid'],
                'goods_id' => $info['goods_id'],
                'sku_id' => $info['sku_id'],
                'is_activity_stock' => mAllActivitySku::USE_ACTIVITY_STOCK,
                'activity_stock' => $info['stock'],
                'actual_stock' => $info['stock'], // todo 如果二次修改的话不能修改这个库存
                'activity_price' => $info['activity_price'],
                'limit_buy_count' => $info['limit_buy_count'],
                'activity_allowance' => $list[$info['sku_id']]['ori_price'] - $info['activity_price'],
                'start_time' => $info['start_time'],
                'end_time' => $info['end_time'],
                'preview_start_time' => $info['start_time'],
                'real_start_time' => $info['start_time'],
                'real_end_time' => $info['end_time'],
                'status' => mAllActivitySku::STATUS_NORMAL,
                'addtime' => date('Y-m-d H:i:s'),
            ];
        }
        return $allActivitySkuList ? : [];
    }

    /**
     * 以时间为key构造数据
     * @param $data
     * @return array
     */
    private static function formatList($data)
    {
        $list = [];
        foreach ($data as $info) {
            if(isset($list[$info['start_time'] . '~' . $info['end_time']])) {
                $list[$info['start_time'] . '~' . $info['end_time']][] = $info;
            } else {
                $list[$info['start_time'] . '~' . $info['end_time']][] = $info;
            }
        }
        return $list;
    }

    /**
     * 初始化结构, 用重新赋值的方式将无效数据过滤
     * @param $data
     * @return array
     */
    private static function formatTime($data)
    {
        $list = [];
        foreach ($data as $key => $info) {
            if($info['goods_id']) {
                $list[$key]['start_time'] = date('Y-m-d H:i:s', strtotime($info['start_time']));
                $list[$key]['end_time'] = date('Y-m-d H:i:s', strtotime($info['end_time']));
                $list[$key]['goods_id'] = $info['goods_id'];
                $list[$key]['sku_id'] = $info['sku_id'];
                $list[$key]['activity_price'] = $info['activity_price'];
                $list[$key]['stock'] = $info['stock'];
                $list[$key]['describe'] = $info['describe'];
                $list[$key]['limit_buy_count'] = $info['limit_buy_count'];
            }
        }
        return $list;
    }

    /**
     * 如果商品价格过低需要二次确认
     * @param $isConfirm
     * @param $data
     * @param $skuInfo
     * @return array|bool
     */
    private static function confirm($isConfirm, $data, $skuInfo)
    {
        $highDisCount = [];
        $lowDisCount  = [];
        if($isConfirm == 0) {
            foreach ($data as $info) {
                if(isset($skuInfo[$info['goods_id']]) && $skuInfo[$info['goods_id']]) {
                    foreach ($skuInfo[$info['goods_id']] as $sku) {
                        if($info['sku_id'] == $sku['sku_id']) {
                            $discount = $info['activity_price'] / $sku['ori_price'];
                            if($discount < 0.8) {
                                $highDisCount[] = $info['sku_id'];
                            } else if($discount > 1) {
                                $lowDisCount[] = $info['sku_id'];
                            }
                        }
                    }
                }
            }

            if($highDisCount) {
                tLog::debug('活动价格二次确认-活动价低于八折', $highDisCount);
                return ['code' => 2, 'msg' => '部分skuId ' . implode("\r\n", $highDisCount) . ' 活动价低于八折，请确认是否提交'];
            } else if($lowDisCount) {
                tLog::debug('活动价格二次确认-活动价大于原价', $lowDisCount);
                return ['code' => 2, 'msg' => '部分skuId ' . implode("\r", $lowDisCount) . ' 活动价大于原价，请确认是否提交'];
            }
        }

        return true;
    }

    /**
     * 验证商品下的sku价格、限购数量、卖点 是否一致
     * @param $list
     * @return array|bool
     */
    private static function checkSkuActivityPrice($list)
    {
        $data = [];
        foreach ($list as $time => $value) {
            foreach ($value as $info) {
                $data[$time][$info['goods_id']]['activity_price'][] = $info['activity_price'];
                $data[$time][$info['goods_id']]['limit_buy_count'][] = $info['limit_buy_count'];
                $data[$time][$info['goods_id']]['describe'][] = $info['describe'];
            }
        }

        foreach ($data as $time => $value) {
            foreach ($value as $info) {
                if(count(array_unique($info['activity_price'])) > 1) {
                    return ['code' => 2, 'msg' => '每个商品下的sku活动价格必须相同'];
                }

                if(count(array_unique($info['limit_buy_count'])) > 1) {
                    return ['code' => 2, 'msg' => '每个商品的限购数量必须一致'];
                }

                if(count(array_unique($info['describe'])) > 1) {
                    return ['code' => 2, 'msg' => '每个商品的卖点必须一致'];
                }
            }
        }
        return true;
    }

    /**
     * 验证商品价格，删除不符合规则的sku
     * @param $data
     * @return array|bool
     */
    private static function checkPrice(&$data)
    {
        $invalidSkuIdList = [];
        foreach ($data as $key => $info) {
            $checkGoodsList = [];
            $checkGoodsList[$info['goods_id']][$info['sku_id']] = $info['activity_price'];
            $checkActivityInfo = [
                'start_time' => $info['start_time'],
                'end_time' => $info['end_time'],
            ];

            $result = AllactivityInfoBak::admCheckActivityPrice($checkGoodsList, $checkActivityInfo, AllactivityInfoBak::ACTIVITY_TYPE_LIMIT_TIME_ROB);

            if(end($result)) {
                $invalidPriceData = end($result);
                $invalidPriceData = reset($invalidPriceData);
                $invalidSkuIdList[] = $invalidPriceData['sku_id'];
                unset($data[$key]);
            }
        }

        if($invalidSkuIdList) {
            return $invalidSkuIdList;
        } else {
            return true;
        }
    }

    /**
     * 验证上传的商品和sku是否存在
     * @param $goodsIds
     * @param $data
     * @return array|bool
     */
    private static function checkGoods($goodsIds, $data)
    {
        $goodsId = array_map('trim', $goodsIds);
        $goodsInfo = sSku::Sku($goodsId, sSku::FIELDS_GROUP_ALL);
        foreach ($data as $item) {

            if(isset($goodsInfo[$item['goods_id']]['sku_info'])) {
                if(array_diff([$item['sku_id']], array_column($goodsInfo[$item['goods_id']]['sku_info'], 'sku_id'))) {
                    return ['code' => 6, 'msg' => '请检查 sku ' . $item['sku_id'] . '是否存在于上传的商品中'];
                }

                foreach ($goodsInfo[$item['goods_id']]['sku_info'] as $info) {
                    if($info['sku_id'] == $item['sku_id']) {
                        if($info['stock'] < $item['stock']) {
                            return ['code' => 6 ,'msg' => 'skuid为' . $item['sku_id'] . '的sku库存不足'];
                        }
                    }
                }

            } else {
                return ['code' => 6 ,'msg' => '商品id为' . $item['goods_id'] . '的商品不存在'];
            }
        }
        return true;
    }

    /**
     * 检验上传商品的活动时间是否有效
     * @param $list
     * @return array|bool
     */
    private static function checkGoodsActivityTime($list)
    {
        $goodsId = [];
        $time = [];
        $invalidGoods = [];
        foreach ($list as $value) {
            foreach ($value as $info) {
                $goodsId[] = $info['goods_id'];
                $time['start_time'] = $info['start_time'];
                $time['end_time'] = $info['end_time'];
            }

            list($goodsId, $invalidData) = AllactivityInfoBak::admCheckActivityTime($goodsId, $time, ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB);
            if($invalidData) {
                $invalidGoods = array_column($invalidData, 'goods_id');
            }
        }

        if(!empty($invalidGoods) && count($invalidGoods) > 1) {
            return ['code' => 3, 'msg' => '部分商品存在于其他活动中 goodsId为' . implode(',', $invalidGoods)];
        } elseif(!empty($invalidGoods)) {
            return ['code' => 3, 'msg' => 'goodsId为 ' . implode(',', $invalidGoods) . ' 的商品存在于其他活动中'];
        }
        return true;
    }

    /**
     * 检查上传的时间是否正常,是否与其它场次冲突
     * @param $list
     * @return array|bool
     */
    private static function checkFlashSaleTime($list)
    {
        $list = array_keys($list);

        $invalid = true;
        foreach ($list as $value) {
            $data = explode('~', $value);
            if(strtotime($data[0]) > strtotime($data[1])) {
                $invalid = false;
                break;
            }
        }
        if($invalid === false) {
            return ['code' => 4, 'msg' => '开始时间不能大于结束时间'];
        }

        $filterList = mFlashSale::getFiledsByFilter();
        foreach ($filterList as $item) {
            foreach ($list as $value) {
                $data = explode('~', $value);
                $startTime = $data[0];
                $endTime = $data[1];
                $timeData = [
                    'start_time' => $startTime,
                    'end_time' => $endTime,
                ];
                $result = self::check($timeData, $item);
                if(!$result) {
                    $invalid = false;
                    break;
                }
            }
            if($invalid === false) {
                break;
            }
        }

        if($invalid === false) {
            return ['code' => 4, 'msg' => '请检查时间范围是否与其他限时购活动重叠'];
        }

        return true;
    }

    /**
     * 验证限时抢时间
     * @param $type
     * @param $flashSaleId
     * @param $sourceTimeData
     * @throws \Exception
     */
    private static function checkFlashSaleTimeWhere($type, $flashSaleId, $sourceTimeData)
    {
        $timeData = [
            'start_time' => $sourceTimeData['start_time'] ?? '',
            'end_time' => $sourceTimeData['end_time'] ?? '',
        ];
        if (isset($sourceTimeData['preview_start_time'])) {
            $timeData['preview_start_time'] = $sourceTimeData['preview_start_time'];
        }
        $filterList = mFlashSale::getFiledsByFilter($type, $flashSaleId);
        foreach ($filterList as $item) {
            $result = self::check($timeData, $item);
            if(!$result) {
                throw new \Exception(vsprintf('与id[%s]限时抢场次时间冲突', [$item['id']]));
            }
        }
    }

    /**
     * 验证文件内的时间是否冲突
     * @param $list
     * @return array|bool
     */
    private static function checkFileTime($list)
    {
        foreach ($list as $key => $info) {
            foreach ($list as $k => $item) {
                if($info['start_time'] != $item['start_time'] && $info['end_time'] != $item['end_time']) {
                    $result =  self::check($info, $item);
                    if(!$result) {
                        return ['code' => 4, 'msg' => '文件中的时间冲突'];
                    }
                }
            }
        }
        return true;
    }

    /**
     * 验证时间
     * @param $timeData
     * @param $checkTimeData
     * @return bool
     */
    private static function check($timeData, $checkTimeData)
    {
        $startTime = strtotime($timeData['start_time'] ?? '');
        $endTime = strtotime($timeData['end_time'] ?? '');

        $checkStartTime = strtotime($checkTimeData['start_time'] ?? '');
        $checkEndTime = strtotime($checkTimeData['end_time'] ?? '');

        $commonCheck = $endTime > $startTime;

        if (isset($timeData['preview_start_time'])) {
            $preTime = strtotime($timeData['preview_start_time']);
            $checkPreTime = strtotime($checkTimeData['preview_start_time'] ?? '');
            $backCheck = $preTime > $checkEndTime;
            $preCheck = $endTime < $checkPreTime;
        } else {
            $backCheck = $startTime > $checkEndTime;
            $preCheck = $endTime < $checkStartTime;
        }

        return $commonCheck && ($backCheck || $preCheck);
    }

    /**
     * 从excel读取数据
     * @param $isConfirm
     * @param $file
     * @return array|mixed
     * @throws \Exception
     */
    private static function getData($isConfirm, $file)
    {
        $data = [];
        if($isConfirm == 0) {
            $upExcel = new UpExcel();
            $file = $upExcel->uploadOne($file);
            $map = [
                '商品ID' => 'goods_id',
                'skuId' => 'sku_id',
                '开始时间' => 'start_time',
                '结束时间' => 'end_time',
//                'sku价格' => 'sku_price',
                '活动价' => 'activity_price',
                '活动库存' => 'stock',
                '卖点' => 'describe',
                '限购数量' => 'limit_buy_count',
            ];

            $data = (new ReadExcel($file))->getExcelData(0, $map, true);
            foreach ($data as $key => $info) {
                $data[$key]['goods_id'] = preg_replace("/\D/","", $info['goods_id']);
                $data[$key]['sku_id'] = preg_replace("/\D/","", $info['sku_id']);
                $data[$key]['stock'] = preg_replace("/\D/","", $info['stock']);
                $data[$key]['limit_buy_count'] = preg_replace("/\D/","", $info['limit_buy_count']);
            }

            cFlashSale::setFlashSale($data, cFlashSale::_CACHE_EXPIRE_TIME, 'adm_upload');
        } else {
            $data = cFlashSale::getFlashSale('adm_upload');
        }

        if($data) {
            $list = array_filter(self::filterArray($data));
            if($list != $data) {
                tLog::debug('上传的文件中含有异常数据', $data);
                return false;
            }
        }

        return $data;
    }

    /**
     * 去除多维数组中的空值
     * @param $arr
     * @param array $values array $values 去除的值  默认 去除  '',null,false,0,'0',[]
     * @return mixed
     */
    private static function filterArray($arr, $values = ['', null, false, 0, '0',[]])
    {
        foreach ($arr as $k => $v) {
            if (is_array($v) && count($v)>0) {
                $arr[$k] = self::filterArray($v, $values);
            }
            if (!$v) {
                unset($arr[$k]);
                break;
            }
        }
        return $arr;
    }

    /**
     * 修改限时抢的开始结束时间
     * @param $flashSale
     * @param $params
     * @param bool $isCheckGoods
     * @return mixed
     * @throws \Exception
     */
    public static function saveFlashSale($flashSale, $params, $isCheckGoods = true)
    {
        $flashSaleId = $flashSale['id'] ?? 0;
        $type = $flashSale['type'] ?? 0;

        if (isset($params['preview_start_time']) && ($params['preview_start_time'] > $params['start_time'])) {
            throw new \Exception('预热时间大于开始时间');
        }

        if($params['start_time'] > $params['end_time']) {
            throw new \Exception('开始时间大于结束时间');
        }

        $result = self::isCanUpdate($flashSaleId);
        if(!$result) {
            throw new \Exception('进行中或者已结束');
        }

        self::checkFlashSaleTimeWhere($type, $flashSaleId, $params);

        $result = mFlashSale::action(function () use($flashSaleId, $type, $params, $isCheckGoods){
            $result = mFlashSale::update($params, ['id' => $flashSaleId])->rowCount();
            if(!$result) {
                throw new \Exception('更新数据失败');
            }

            $limitTimeRobbing   = mLimitTimeRobbing::select('*', ['flash_sale_id' => $flashSaleId, 'status' => mLimitTimeRobbing::STATUS_NORMAL]);
            $limitTimeRobbingId = array_column($limitTimeRobbing, 'id');
            $limitTimeRobbingSku = mLimitTimeRobbingSku::select('id', ['robbing_id' => $limitTimeRobbingId, 'status' => mLimitTimeRobbingSku::STATUS_NORMAL]);

            // 如果修改时间的时候goods表有数据的话,将时间同步至goods表
            if($limitTimeRobbing) {
                foreach ($limitTimeRobbing as $info) {
                    list($goodsId, $invalidData) = AllactivityInfoBak::admCheckActivityTime([$info['goods_id']], $params, ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB, $flashSaleId);
                    if($invalidData) {
                        tLog::debug('限时抢内的商品活动时间冲突', [$flashSaleId => $params, $invalidData]);
                        throw new \Exception('限时抢内的商品活动时间冲突');
                    }
                }

                if (!key_exists('preview_start_time', $params)) {
                    $result = mLimitTimeRobbing::update($params, ['flash_sale_id' => $flashSaleId])->rowCount();
                    if(!$result) {
                        throw new \Exception('更新限时抢spu表失败');
                    }
                }
            }

            // 如果修改时间的时候sku表有数据的话,将数据同步至sku表以及活动总信息表中
            if($limitTimeRobbingSku) {
                if (!key_exists('preview_start_time', $params)) {
                    $result = mLimitTimeRobbingSku::update($params, ['robbing_id' => $limitTimeRobbingId])->rowCount();
                    if (!$result) {
                        throw new \Exception('更新限时抢sku表失败');
                    }
                }

                $result = AllActivityInfo::admUpdateActivityAttr($flashSaleId, $type, [$params], self::ALL_ACTIVITY_MAP[$type]);
                if(!$result) {
                    throw new \Exception('更新总活动表失败');
                }
            }

            return true;
        });
        return $result;
    }

    private static function delAllActivityInfoProcess($flashSaleId, $type)
    {
        $result = AllActivityInfo::admDelActivityInfo($flashSaleId, $type, self::ALL_ACTIVITY_MAP[$type]);
        if(!$result) throw new \Exception('更新活动汇总表状态失败');
    }

    private static function delLimitTimeRobbingSkuProcess($where)
    {
        $result = mLimitTimeRobbingSku::update(['status' => mLimitTimeRobbingSku::STATUS_DEL], $where)->rowCount();
        if(!$result) throw new \Exception('更新限时购sku表状态失败');
    }

    private static function delLimitTimeRobbingProcess($adminId, $where)
    {
        $result = mLimitTimeRobbing::update(['status' => mLimitTimeRobbing::STATUS_DEL, 'admin_id' => $adminId], $where)->rowCount();
        if(!$result) throw new \Exception('更新限时购商品表状态失败');
    }

    /**
     * 删除一场活动
     * @param $flashSaleId
     * @param $adminId
     * @return mixed
     */
    public static function delFlashSale($flashSaleId, $adminId)
    {
        mFlashSale::action(function () use($flashSaleId, $adminId) {
            $flashSale = mFlashSale::get('*', ['id' => $flashSaleId]);
            $type = $flashSale['type'] ?? ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB;

            $result = mFlashSale::update(['status' => mFlashSale::STATUS_DELETE, 'admin_id' => $adminId], ['id' => $flashSaleId])->rowCount();
            if(!$result)  throw new \Exception('更新限时购主表状态失败');

            $robbingIds = mLimitTimeRobbing::select('id', ['flash_sale_id' => $flashSaleId, 'status' => mLimitTimeRobbing::STATUS_NORMAL]);

            if($robbingIds) {
                self::delLimitTimeRobbingProcess($adminId, ['flash_sale_id' => $flashSaleId]);
            }

            $robbingSkuIds = empty($robbingIds) ? [] : mLimitTimeRobbingSku::select('id', ['robbing_id' => $robbingIds, 'status' => mLimitTimeRobbingSku::STATUS_NORMAL]);
            if($robbingSkuIds) {
                self::delLimitTimeRobbingSkuProcess(['robbing_id' => $robbingSkuIds]);

                self::delAllActivityInfoProcess($flashSaleId, $type);
            }
        });
    }

    /**
     * 删除一个商品
     * @param $flashSaleId
     * @param $robbingId
     * @param $adminId
     * @return mixed
     */
    public static function delFlashSaleGoods($flashSaleId, $robbingId, $adminId)
    {
        mLimitTimeRobbing::action(function () use($flashSaleId, $robbingId, $adminId) {
            $flashSale = mFlashSale::get('*', ['id' => $flashSaleId]);
            $type = $flashSale['type'] ?? ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB;

            $robbingList = mLimitTimeRobbing::select('*', ['id' => $robbingId, 'status' => mLimitTimeRobbing::STATUS_NORMAL]);
            $goodsIds = array_column($robbingList, 'goods_id');
            $robbingSkuList = mLimitTimeRobbingSku::select('*', ['robbing_id' => $robbingId, 'status' => mLimitTimeRobbingSku::STATUS_NORMAL]);

            if($robbingSkuList) self::delLimitTimeRobbingSkuProcess(['robbing_id' => $robbingId]);

            if($robbingList) {
                self::delLimitTimeRobbingProcess($adminId, ['id' => $robbingId]);

                $result = AllActivityInfo::admDelActivityByGoodsId($flashSaleId, $type, $goodsIds, self::ALL_ACTIVITY_MAP[$type]);
                if(!$result) throw new \Exception('更新活动汇总表状态失败');
            }
        });
    }

    /**
     * 删除一个sku
     * @param $flashSaleId
     * @param $robbingId
     * @param $robbingSkuId
     * @param $adminId
     * @return mixed
     */
    public static function delFlashSaleSku($flashSaleId, $robbingId, $robbingSkuId, $adminId)
    {
        $robbingSku = mLimitTimeRobbingSku::get('*', ['id' => $robbingSkuId]);

        mLimitTimeRobbingSku::action(function () use($flashSaleId, $robbingId, $robbingSkuId, $adminId, $robbingSku) {
            $flashSale = mFlashSale::get('*', ['id' => $flashSaleId]);
            $type = $flashSale['type'] ?? ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB;

            self::delLimitTimeRobbingSkuProcess(['id' => $robbingSkuId]);

            $result = AllActivityInfo::admDelActivityBySkuId($flashSaleId, $type, $robbingSku['goods_id'], $robbingSku['sku_id'], self::ALL_ACTIVITY_MAP[$type]);
            if(!$result) throw new \Exception('更新活动汇总表状态失败');
        });
    }

    /**
     * 选择参加限时抢的sku
     * @param $flashSaleId
     * @param $robbingId
     * @param $skuIds
     * @throws \Exception
     */
    public static function saveSkuId($flashSaleId, $robbingId, $skuIds)
    {
        if(!self::isCanUpdate($flashSaleId)) {
            tLog::debug('限时抢进行中或者已结束', [$flashSaleId, $skuIds]);
            throw new \Exception('限时抢进行中或者已结束');
        }
        // 如果有sku的情况下,需要同步sku  all_goods all_sku表
        mLimitTimeRobbingSku::action(function () use($flashSaleId, $robbingId, $skuIds) {
            $flashSale = mFlashSale::get('*', ['id' => $flashSaleId]);
            $type = $flashSale['type'] ?? ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB;

            $robbingList= mLimitTimeRobbing::get('*', ['id' => $robbingId]);

            $preview_start_time = $type == ActivityInfo::ACTIVITY_TYPE_ZHUYOUJINTIE ? $flashSale['preview_start_time'] : $robbingList['start_time'];

            $list = [];
            foreach ($skuIds as $skuId) {
                $list[] = [
                    'robbing_id' => $robbingId,
                    'shop_id' => $robbingList['shop_id'],
                    'goods_id' => $robbingList['goods_id'],
                    'sku_id' => $skuId,
                    'buy_price' => $robbingList['buy_price'],
                    'start_time' => $robbingList['start_time'],
                    'end_time' => $robbingList['end_time'],
                    'status' => mLimitTimeRobbingSku::STATUS_NORMAL,
                ];
            }

            $result = mLimitTimeRobbingSku::insert($list)->rowCount();
            if(!$result) throw new \Exception('添加限时抢商品失败');

            $goodsData[] = [
                'activity_id' => $flashSaleId,
                'type' => $type,
                'shop_id' => $robbingList['shop_id'],
                'goods_id' => $robbingList['goods_id'],
                'start_time' => $robbingList['start_time'],
                'end_time' => $robbingList['end_time'],
                'preview_start_time' => $preview_start_time,
                'real_start_time' => $robbingList['start_time'],
                'real_end_time' => $robbingList['end_time'],
                'addtime' => date('Y-m-d H:i:s'),
                'status' => mAllActivityGoods::STATUS_NORMAL,
            ];


            $skuInfo = sSku::Sku([$robbingList['goods_id']], sSku::FIELDS_GROUP_SKU_INFO);
            foreach ($skuInfo[$robbingList['goods_id']] as $sku) {
                $skuList[$sku['sku_id']] = $sku;
            }
            $skuData = [];
            foreach ($skuIds as $skuId) {
                $skuData[] = [
                    'activity_id' => $flashSaleId,
                    'type' => $type,
                    'shop_id' => $robbingList['shop_id'],
                    'goods_id' => $robbingList['goods_id'],
                    'sku_id' => $skuId,
                    'activity_price' => $robbingList['buy_price'],
                    'limit_buy_count' => $robbingList['buy_limit'],
                    'activity_allowance' => $skuList[$skuId]['ori_price'] - $robbingList['buy_price'],
                    'start_time' => $robbingList['start_time'],
                    'end_time' => $robbingList['end_time'],
                    'preview_start_time' => $preview_start_time,
                    'real_start_time' => $robbingList['start_time'],
                    'real_end_time' => $robbingList['end_time'],
                    'addtime' => date('Y-m-d H:i:s'),
                    'status' => mAllActivityGoods::STATUS_NORMAL,
                ];
            }

            $result = AllActivityInfo::admUpdateActivityInfo($flashSaleId, $type, $goodsData, $skuData, self::ALL_ACTIVITY_MAP[$type], false);

            if(!$result) throw new \Exception('添加活动汇总表信息失败');

        });
    }

    /**
     * 添加限时抢
     * @param $flashSaleId
     * @param $params
     * @return bool
     * @throws \Exception
     */
    public static function addFlashSale($flashSaleId, $params)
    {
        $type = $params['type'] ?? 0;

        self::checkFlashSaleTimeWhere($type, $flashSaleId, $params);

        if($flashSaleId > 0) {
            $flashSaleId = mFlashSale::updateFlashSale($flashSaleId, ['type' => $type, 'start_time' => $params['start_time'], 'end_time' => $params['end_time']]);
        } else {
            $insertData = ['type' => $type, 'start_time' => $params['start_time'], 'end_time' => $params['end_time']];
            if($type == ActivityInfo::ACTIVITY_TYPE_ZHUYOUJINTIE) $insertData['preview_start_time'] = $params['preview_start_time'];
            mFlashSale::insert($insertData)->rowCount();
            $flashSaleId = mFlashSale::id();
        }

        return $flashSaleId;
    }

    /**
     * 添加限时抢商品
     * limit_time_robbing
     * @param $flashSaleId
     * @param $goodsIds
     * @return mixed
     * @throws \Exception
     */
    public static function flashSaleAddGoods($flashSaleId, $goodsIds)
    {
        if(!self::isCanUpdate($flashSaleId)) {
            throw new \Exception('限时抢已结束');
        }

        $robbingList = mLimitTimeRobbing::select('id', ['flash_sale_id' => $flashSaleId, 'goods_id' => $goodsIds, 'status' => mLimitTimeRobbing::STATUS_NORMAL]);
        if($robbingList) {
            throw new \Exception('添加的商品已存在限时抢活动中');
        }

        $flashSale = mFlashSale::get('*', ['id' => $flashSaleId, 'status' => mFlashSale::STATUS_NORMAL]);
        $type = $flashSale['type'] ?? ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB;
        if ($type == ActivityInfo::ACTIVITY_TYPE_ZHUYOUJINTIE) {
            $activityTime = [
                'start_time' => $flashSale['start_time'],
                'end_time' => $flashSale['end_time'],
                'preview_start_time' => $flashSale['preview_start_time'],
            ];
        } else {
            $activityTime = [
                'start_time' => $flashSale['start_time'],
                'end_time' => $flashSale['end_time'],
            ];
        }

        list($goodsId, $invalidData) = AllactivityInfoBak::admCheckActivityTime($goodsIds, $activityTime, $type, $flashSaleId);
        if($invalidData) {
            throw new \Exception('商品活动时间冲突');
        }

        $goodsList = sGoods::Goods($goodsIds, sGoods::FIELDS_GROUP_BASE);

        if (empty($goodsList)) throw new \Exception('商品信息不存在');

        $list = [];
        foreach ($goodsIds as $goodsId) {
            if(isset($goodsList[$goodsId]) && $goodsList[$goodsId]['status'] == mGoodsBasicInfo::STATUS_ONLINE) {
                $list[] = [
                    'flash_sale_id' => $flashSaleId,
                    'shop_id' => $goodsList[$goodsId]['uid'],
                    'goods_id' => $goodsId,
                    'start_time' => $flashSale['start_time'],
                    'end_time' => $flashSale['end_time'],
                    'status' => mLimitTimeRobbing::STATUS_NORMAL,
                ];
            }

        }

        return mLimitTimeRobbing::insert($list)->rowCount();
    }

    /**
     * 选择sku所需要的数据
     * @param $robbingId
     * @return array
     */
    public static function flashSaleSkuEdit($robbingId)
    {
        $selectSku = [];
        $robbingList = mLimitTimeRobbing::select('*', ['id' => $robbingId, 'status' => mLimitTimeRobbing::STATUS_NORMAL]);
        $goodsIds = array_column($robbingList , 'goods_id');
        $list = mLimitTimeRobbingSku::select('*', ['robbing_id' => $robbingId, 'status' => mLimitTimeRobbingSku::STATUS_NORMAL]);
        $selectedSkuId = array_column($list, 'sku_id');

        $skuList = sSku::sku($goodsIds, sSku::FIELDS_GROUP_ALL);
        Log::info('sku选择', compact('skuList', 'selectedSkuId'));
        $skuList = $skuList[$goodsIds[0]]['sku_info'];
        $skuList = array_column($skuList, null, 'sku_id');
        $skuIds = array_values(array_diff(array_keys($skuList), $selectedSkuId));

        foreach ($skuIds as $skuId) {
            foreach ($skuList as $info) {
                if($skuId == $info['sku_id'] && $info['stock'] > 0) {
                    $selectSku[$info['sku_id']] = 'sku_id ' . $info['sku_id']. ' sku名称 ' . $info['sku_desc'];
                }
            }
        }

        return $selectSku;
    }

    /**
     * 修改sku维度相关信息
     * @param $flashSaleId
     * @param $robbingId
     * @param $robbingSkuId
     * @param $params
     * @throws \Exception
     */
    public static function flashSaleSkuSave($flashSaleId, $robbingId, $robbingSkuId, $params)
    {
        if(!self::isCanUpdate($flashSaleId)) {
            throw new \Exception('限时抢进行中或者已结束');
        }
        $name = $params['name'] ?? '';
        $goodsId = mLimitTimeRobbing::get('goods_id', ['id' => $robbingId, 'flash_sale_id' => $flashSaleId]);
        $skuId   = mLimitTimeRobbingSku::get('sku_id', ['id' => $robbingSkuId, 'status' => mLimitTimeRobbingSku::STATUS_NORMAL]);
        switch ($name) {
            case 'buy_price':
                $price = floatval($params['value']);

                if($price <= 0) {
                    throw new \Exception('价格不能小于0');
                }

                $robbingSkuData = ['buy_price' => $price];

                $skuData[] = [
                    'goods_id' => $goodsId,
                    'sku_id' => $skuId,
                    'activity_price' => $price,
                ];
                break;
            case 'start_stock':
                $stock = intval($params['value']);

                if($stock < 0) {
                    throw new \Exception('sku库存小于0或者不是整数');
                }

                $robbingSkuData = ['start_stock' => $stock, 'promo_stock' => $stock];

                $skuData[] = [
                    'goods_id' => $goodsId,
                    'sku_id' => $skuId,
                    'activity_stock' => $stock,
                    'actual_stock' => $stock,
                    'is_activity_stock' => 1
                ];
                break;
            default:
                throw new \Exception('未开发的修改字段');
                break;
        }

        mLimitTimeRobbingSku::action(function () use($flashSaleId, $robbingId, $robbingSkuId, $robbingSkuData, $skuData) {
            $result = mLimitTimeRobbingSku::update($robbingSkuData, ['id' =>$robbingSkuId])->rowCount();
            if(!$result) throw new \Exception('更新限时抢sku表失败');

            $flashSale = mFlashSale::get('*', ['id' => $flashSaleId]);
            $type = $flashSale['type'] ?? AllActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB;
            AllActivityInfo::admUpdateActivitySkuInfo($flashSaleId, $type, $skuData);
        });

        if ($goodsId > 0) AllActivityBak::delItem($goodsId);
    }

    /**
     * 修改商品维度信息, 不同的信息需要用不同的方式处理
     * @param $flashSaleId
     * @param $robbingId
     * @param $data
     * @return bool|mixed
     * @throws \Exception
     */
    public static function flashSaleGoodsSave($flashSaleId, $robbingId, $data)
    {
        if(!self::isCanUpdate($flashSaleId)) {
            tLog::debug('限时抢进行中或者已结束', [$flashSaleId, $robbingId, $data]);
            throw new \Exception('限时抢进行中或者已结束');
        }
        $result = true;
        if($data['name'] == 'describe') {
            if(!$data['value']) {
                tLog::debug('限时购卖点不能为空', [$flashSaleId, $data]);
                throw new \Exception('限时购卖点不能为空');
            }
            // 只需要修改goods表数据
            $result = mLimitTimeRobbing::updateRobbing([$data['name'] => $data['value']], ['id' => $robbingId, 'flash_sale_id' => $flashSaleId])->rowCount();
        } else if($data['name'] == 'buy_price') {
            if(!$data['value']) {
                tLog::debug('限时购价格不能为空', [$flashSaleId, $data]);
                throw new \Exception('限时购价格不能为空');
            }
            // 需要同步goods sku  all_sku
            $flashSale = mFlashSale::get('*', ['id' => $flashSaleId]);
            $goodsId = mLimitTimeRobbing::get('goods_id', ['id' => $robbingId, 'flash_sale_id' => $flashSaleId]);
            $maxPrice = mGoodsBasicInfo::get('max_price', ['goods_id' => $goodsId]);
            if($data['value'] > $maxPrice) {
                tLog::debug('限时购价格大于商品原价', [$flashSaleId, $data]);
                throw new \Exception('限时购价格大于商品原价');
            }

            $skuIds  = mLimitTimeRobbingSku::select('sku_id', ['robbing_id' => $robbingId, 'status' => mLimitTimeRobbingSku::STATUS_NORMAL]);
            if(!$skuIds) {
                tLog::debug('请先添加该商品的sku', [$flashSaleId, $data]);
                throw new \Exception('请先添加该商品的sku');
            }

            $checkGoodsList[$goodsId] = array_fill_keys($skuIds, $data['value']);
            $checkActivityInfo = [
                'start_time' => $flashSale['start_time'],
                'end_time' => $flashSale['end_time'],
            ];

            //todo
            $type = $flashSale['type'] ?? AllactivityInfoBak::ACTIVITY_TYPE_LIMIT_TIME_ROB;
            $result = AllactivityInfoBak::admCheckActivityPrice($checkGoodsList, $checkActivityInfo, $type);

            if(end($result)) {
                $invalidPriceData = end($result);
                $skuInfos = sSku::Sku([$goodsId], sSku::FIELDS_GROUP_ALL);
                $skuInfos = array_column($skuInfos[$goodsId]['sku_info'], null, 'sku_id');

                $invalidPriceData = reset($invalidPriceData);
                throw new \Exception('sku ' . $skuInfos[$invalidPriceData['sku_id']]['sku_desc'] . ' 的限时购价格 ' . $data['value'] . ' 高于同时段的商家直降价 ' . $invalidPriceData['activity_price'] . ' ，请修改后再保存');
            }


            $result  = mLimitTimeRobbing::action(function () use ($flashSaleId, $robbingId, $goodsId, $skuIds, $data) {
                $result = mLimitTimeRobbing::update(['buy_price' => $data['value']], ['id' => $robbingId, 'status' => mLimitTimeRobbing::STATUS_NORMAL])->rowCount();
                if(!$result) {
                    return false;
                }

                $result = mLimitTimeRobbingSku::update(['buy_price' => $data['value']], ['robbing_id' => $robbingId, 'status' => mLimitTimeRobbingSku::STATUS_NORMAL])->rowCount();
                if(!$result) {
                    return false;
                }

                $goodsData[] = [
                    'goods_id' => $goodsId,
                ];
                $skuInfo = sSku::Sku([$goodsId], sSku::FIELDS_GROUP_SKU_INFO);
                foreach ($skuInfo[$goodsId] as $sku) {
                    $skuList[$sku['sku_id']] = $sku;
                }

                foreach ($skuIds as $skuId) {
                    $skuData[] = [
                        'goods_id' => $goodsId,
                        'sku_id' => $skuId,
                        'activity_price' => $data['value'],
                        'activity_allowance' => $skuList[$skuId]['ori_price'] - $data['value'],
                    ];
                }

                $flashSale = mFlashSale::get('*', ['id' => $flashSaleId]);
                $type = $flashSale['type'] ?? AllActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB;
                $result = AllActivityInfo::admUpdateActivityInfo($flashSaleId, $type, $goodsData, $skuData, self::ALL_ACTIVITY_MAP[$type], false);

                AllActivityBak::delItem($goodsId);
                if(!$result) {
                    return false;
                }

                return true;
            });
        } else if($data['name'] == 'buy_limit') {
            if(!$data['value']) {
                tLog::debug('限时购限购数量输入不正确', [$flashSaleId, $data]);
                throw new \Exception('限时购限购数量输入不正确');
            }
            // 需要同步 goods   all_sku
            $goodsId = mLimitTimeRobbing::get('goods_id', ['id' => $robbingId, 'flash_sale_id' => $flashSaleId]);
            $skuIds = mLimitTimeRobbingSku::select('sku_id', ['robbing_id' => $robbingId, 'status' => mLimitTimeRobbingSku::STATUS_NORMAL]);

            $result = mLimitTimeRobbing::action(function () use ($flashSaleId, $robbingId, $goodsId, $skuIds, $data) {

                $result = mLimitTimeRobbing::update(['buy_limit' => $data['value']], ['id' => $robbingId, 'status' => mLimitTimeRobbing::STATUS_NORMAL])->rowCount();
                if(!$result) {
                    return false;
                }

                if($skuIds) {
                    $goodsData[] = [
                        'goods_id' => $goodsId,
                    ];
                    foreach ($skuIds as $skuId) {
                        $skuData[] = [
                            'goods_id' => $goodsId,
                            'sku_id' => $skuId,
                            'limit_buy_count' => $data['value'],
                        ];
                    }
                    $flashSale = mFlashSale::get('*', ['id' => $flashSaleId]);
                    $type = $flashSale['type'] ?? AllActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB;
                    $result = AllActivityInfo::admUpdateActivityInfo($flashSaleId, $type, $goodsData, $skuData, self::ALL_ACTIVITY_MAP[$type], false);
                    if(!$result) {
                        return false;
                    }
                }

                return true;
            });
        }

        return $result;
    }

    /**
     * goods信息页面
     * @param $where
     * @return array
     */
    public static function admFlashSaleGoodsList($where)
    {
        $list = mLimitTimeRobbing::select('*', $where);
        $robbingId = array_column($list, 'id');
        $goodsIds = array_column($list, 'goods_id');
        $shopIds = array_column($list, 'shop_id');
        $goodsInfo = sGoods::Goods($goodsIds, sGoods::FIELDS_GROUP_ADMIN);
        $shopInfo = sShopInfo::getShopInfoList($shopIds, 'admin');
        $robbingSkuList = mLimitTimeRobbingSku::select('*', ['robbing_id' => $robbingId, 'status' => mLimitTimeRobbingSku::STATUS_NORMAL]);
        $robbingSkuListMap = [];
        if ($robbingSkuList) {
            foreach ($robbingSkuList as $skuList) {
                $robbingSkuListMap[$skuList['robbing_id']][] = $skuList;
            }
        }
        $skuInfo = sSku::getInfo($goodsIds, ActivityInfo::ACTIVITY_TYPE_ZHUYOUJINTIE);

        foreach ($list as $key => $info) {
            $goodsId = $info['goods_id'];
            $tempSkuInfo = $skuInfo[$goodsId] ?? [];
            $skus = [];
            if (isset($robbingSkuListMap[$info['id']])) {
                foreach ($robbingSkuListMap[$info['id']] as $v) {
                    $sku_id = $v['sku_id'];
                    $item = $tempSkuInfo[$sku_id] ?? [];
                    $skus[] = [
                        'sku_id' => $sku_id,
                        '属性' => $item['sku_desc'] ?? '-',
                        '原价' => $item['price'] ?? '-',
                        '活动价' => $item['activity_price'] ?? '-',
                        '实际库存' => $item['stock'] ?? '-',
                        '初始设置活动库存' => $v['start_stock'],
                        '活动库存' => $item['activity_stock'] ?? '-',
                    ];
                }
                //按sku_id升序排序
                if ($skus) {
                    $sku_id = array_column($skus, 'sku_id');
                    array_multisort($sku_id,SORT_ASC, $skus);
                }
            }
            $temp = [
                'cover_img' => $goodsInfo[$goodsId]['cover_img'],
                'shop_name' => $shopInfo[$info['shop_id']]['name'],
                'skus' => $skus,
            ];
            $list[$key] = $info + $temp;
        }

        return ['list' => $list, 'total' => count($list)];
    }

    /**
     * 获取sku信息
     * @param $where
     * @return array
     */
    public static function admFlashSaleSkuList($where)
    {
        $list = mLimitTimeRobbingSku::select_master('*', $where);
        $count = mLimitTimeRobbingSku::count_master('*', $where['AND'] ?? []);

        $goodsIds = array_column($list, 'goods_id');
        $skuInfo= sSku::Sku($goodsIds, sSku::FIELDS_GROUP_ALL);

        foreach ($list as $key => $info) {
            foreach ($skuInfo[$goodsIds[0]]['sku_info']  as $item) {
                if($item['sku_id'] == $info['sku_id']) {
                    $list[$key]['sku_name'] = $item['sku_desc'];
                }
            }
        }
        return ['list' => $list, 'total' => $count];
    }

}